package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.Vo.MenuVO;
import com.example.entity.Menu;
import com.example.entity.User;
import com.example.mapper.MenuMapper;
import com.example.service.IMenuService;
import com.example.service.IUserService;
import com.example.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ptuDai
 * @since 2022-03-05
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    IUserService userService;

    @Autowired
    RedisService redisService;

    /**
     * 获取当前用户菜单导航
     */
    @Override
    public List<MenuVO> getCurrentUserNav() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User sysUser = userService.getByUserName(username);
        // 获取用户的所有菜单
        List<Menu> menus = userService.getNavMenus(sysUser.getId());
        List<Menu> treeMenus = buildTreeMenu(menus);
        return convert(treeMenus);
    }

    @Override
    public List<Menu> tree() {
        List<Menu> menus = buildTreeMenu(this.list(new QueryWrapper<Menu>().orderByDesc("order_num")));
        return menus;
    }

    /**
     * 把list转成树形结构的数据
     */
    private List<Menu> buildTreeMenu(List<Menu> menus) {
        List<Menu> finalMenus = new ArrayList<>();
        for (Menu menu : menus) {
            // 先寻找各自的孩子
            for (Menu e : menus) {
                if (e.getParentId().equals(menu.getId())) {
                    menu.getChildren().add(e);
                }
            }
            // 提取出父节点
            if (menu.getParentId() == 0) {
                finalMenus.add(menu);
            }
        }
        return finalMenus;
    }

    /**
     * menu转menuVO
     */
    private List<MenuVO> convert(List<Menu> menus) {
        List<MenuVO> menuVO = new ArrayList<>();
        menus.forEach(m -> {
            MenuVO vo = new MenuVO();
            vo.setId(m.getId());
            vo.setName(m.getName());
            vo.setTitle(m.getTitle());
            vo.setComponent(m.getComponent());
            vo.setIcon(m.getIcon());
            vo.setPath(m.getPath());
            if (m.getChildren().size() > 0) {
                vo.setChildren(convert(m.getChildren()));
            }
            menuVO.add(vo);
        });
        return menuVO;
    }
}
